package org.jetlinks.community.mstn;

import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.web.api.crud.entity.QueryParamEntity;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.exception.BusinessException;
import reactor.core.publisher.Mono;

import java.io.Serializable;

public class MstnBaseController {

    /**
     * 获取当前用户的项目ID
     * @return
     */
    public Mono<String> getProjectId() {
        return Authentication.currentReactive().map(auth -> {
            Serializable orgSerializable = auth.getAttribute("tenantId").orElseThrow(()->new BusinessException("该用户没有项目"));
            return (String) orgSerializable;
        });
    }
    /**
     * 获取当前项目资产查询条件
     */
    public Mono<QueryParamEntity> getAssets(String assetsType, boolean exits , Mono<QueryParamEntity> queryParamEntityMono) {
        return Mono.zip(Authentication.currentReactive(), queryParamEntityMono).flatMap(tuple -> {
           Authentication auth = tuple.getT1();
            Serializable orgSerializable = auth.getAttribute("tenantId").orElseThrow(()->new BusinessException("该用户没有资产"));
            String projectId = (String) orgSerializable;
            Term term = new Term();
            term.setValue(projectId);
            term.setTermType("mstn-assets$"+ assetsType + "$in" + (!exits?"":"$not"));
            term.setColumn("id");
            QueryParamEntity query = tuple.getT2();
            query.addTerm(term);
            return Mono.just(query);
        });
    }

    /**
     * 获取当前用户的站点ID
     * @return
     */
    public Mono<String> getSiteId() {
        return Authentication.currentReactive().map(auth -> {
            Serializable orgSerializable = auth.getAttribute("default-org").orElseThrow(()->new BusinessException("该用户没有设置默认站点"));
            return (String) orgSerializable;
        });
    }

    /**
     * 获取当前用户ID
     * @return
     */
    public Mono<String> getCurrentUserId() {
        return Authentication.currentReactive().map(auth -> auth.getUser().getId());
    }
}
